package com.eimf.saf.base.exception;

import org.apache.log4j.Logger;

/**
 * @author eden
 * @date 2013-11-19 下午3:08:29
 * @Description: 异常处理基类
 */
public class SafException extends Exception
{
    private static final long serialVersionUID = 1L;
    protected static Logger logger = Logger.getLogger(SafException.class.getName());
    protected Throwable cause;

    /*
     * SAF默认的异常，异常信息内置为Error occurred in SAF application.
     */
    public SafException()
    {
        super("Error occurred in SAF application.");
    }

    /*
     * 自定义异常信息的PORTAL应用异常
     */
    public SafException(final String message)
    {
        super(message);
    }

    /*
     * 转化外部异常为PORTAL应用异常
     */
    public SafException(final String message, final Throwable cause)
    {
        super(message);
        this.cause = cause;
    }

    /*
     * 获取被包装的异常
     */
    @Override
    public Throwable initCause(final Throwable cause)
    {
        this.cause = cause;
        return cause;
    }

    /*
     * 获取异常信息
     */
    @Override
    public String getMessage()
    {
        // Get this exception"s message.
        String msg = super.getMessage();
        msg = msg == null ? "" : msg;
        if (cause != null)
        {
            msg += " ; " + cause.getMessage();
        }
        return msg;
    }

    /*
     * 打印堆栈追踪
     */
    @Override
    public void printStackTrace()
    {
        if (cause != null)
        {
            cause.printStackTrace();
        } else
        {
            super.printStackTrace();
        }

    }

    private String makeStackTrace()
    {
        StackTraceElement[] arr = super.getStackTrace();
        if (arr == null || arr.length <= 0)
        {
            arr = cause.getStackTrace();
        }
        final StringBuilder strBld = new StringBuilder();
        for (int i = 0; i < arr.length; i++)
        {
            strBld.append(arr[i]);
            if (i >= 3)
            {
                break;
            }
        }
        return strBld.toString();
    }

    /*
     * 记录Error级别的日志到日志文件，记录堆栈的开始部分信息
     */
    public void logStackTrace()
    {

        SafException.logger.error(makeStackTrace());
    }

    /*
     * 获取简单的堆栈信息
     */
    public String getSimpleStackTrace()
    {
        return makeStackTrace();
    }

    /*
     * 记录异常信息到日志文件
     */
    public void logMessage()
    {
        SafException.logger.error(getMessage());
    }

    @Override
    public Throwable getCause()
    {
        return cause;
    }
}
